package com.supply.hsa.link.controller;

import com.fangcang.common.ResponseDTO;
import com.fangcang.common.util.StringUtil;
import com.fangcang.hotelinfo.dto.BedTypeDTO;
import com.fangcang.hotelinfo.dto.HotelFacilityDTO;
import com.fangcang.hotelinfo.request.HotelInfoRequestDTO;
import com.fangcang.hotelinfo.request.RoomTypeRequestDTO;
import com.fangcang.hotelinfo.response.HotelInfoResponseDTO;
import com.fangcang.hotelinfo.service.HotelInfoService;
import com.fangcang.hotelinfo.service.RoomTypeService;
import com.supply.hsa.link.common.constant.SupplierClass;
import com.supply.hsa.link.common.constant.SystemConstants;
import com.supply.hsa.link.common.dto.HotelMappingDTO;
import com.supply.hsa.link.common.dto.RoomMappingDTO;
import com.supply.hsa.link.common.server.SupplyDataMappingServer;
import com.supply.hsa.link.hotelinfo.dto.SupplyHotelDTO;
import com.supply.hsa.link.hotelinfo.dto.SupplyRoomDTO;
import com.supply.hsa.link.hotelinfo.server.HotelInfoSyncService;
import com.supply.hsa.link.hotelinfo.server.RoomTypeSyncService;
import com.supply.hsa.link.hotelinfo.server.SupplyHotelStaticServer;
import com.supply.hsa.sync.ean.*;
import com.supply.hsa.sync.ean.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.*;

@Controller
@Slf4j
@RequestMapping("/ean")
public class EanHotelStaticController {

    @Autowired
    private SupplyHotelStaticServer supplyHotelStaticServer;
    @Autowired
    private HotelInfoSyncService hotelInfoSyncService;
    @Autowired
    private RoomTypeSyncService roomTypeSyncService;
    @Autowired
    private SupplyDataMappingServer supplyDataMappingServer;

    @ResponseBody
    @RequestMapping(value = "/syncHotelInfo", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    public String syncHotelInfo(@RequestParam String supplyCode, String regions, String hotelIds) {
        /**
         * 第一步
         * 1、根据区域id循环调用供应商获取该区域下的酒店id
         * 2、拿到所有酒店后根据固定的酒店量调用供应商查询酒店接口获取酒店信息，中文版都查询
         */
        String[] ids = regions.split(",");
        ApiServiceRapid repidApi = new ApiServiceRapid();

        String type_city = "city_";
        String type_province = "province_state_";
        int oneSize = 50;//每次获取10个酒店数据

        HashSet<String> hotelIdSet = new HashSet<>();
        //记录酒店对应的城市编码
        Map<String, String> hotelCityMap = new HashMap<>();//key为city_hotelid, value 为cityid
        //记录酒店对应的省份编码
        Map<String, String> hotelProvinceMap = new HashMap<>();
        if(StringUtil.isValidString(hotelIds)){
            hotelIdSet.addAll(Arrays.asList(hotelIds.split(",")));
        }else {
            for (String regionId : ids) {
                RegionDescendants regionDescendants = repidApi.queryHotelIds(regionId, supplyCode);

                if (regionDescendants != null && regionDescendants.getRegionMap() != null) {
                    for (String key1 : regionDescendants.getRegionMap().keySet()) {
                        Map<String, Region> regionMap = regionDescendants.getRegionMap().get(key1);

                        if (regionMap != null) {
                            for (String key2 : regionMap.keySet()) {
                                Region region = regionMap.get(key2);
                                //仅取省份城市节点下的酒店编码
                                if ((type_city.contains(region.getType()) || type_province.contains(region.getType())) && region.getProperty_ids() != null) {
                                    hotelIdSet.addAll(region.getProperty_ids());

                                    if (type_city.contains(region.getType())) {
                                        for (String tempId : region.getProperty_ids()) {
                                            hotelCityMap.put(type_city + tempId, region.getId());
                                        }
                                    } else {
                                        for (String tempId : region.getProperty_ids()) {
                                            hotelProvinceMap.put(type_province + tempId, region.getId());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        int allIdSize = hotelIdSet.size();
        if (allIdSize > 0) {
            List<String> tempIdsList = new ArrayList<String>();
            int i = 0;
            for (String hotelId : hotelIdSet) {
//                hotelId="31951157";
                tempIdsList.add(hotelId);
                i = i + 1;

                if (i % oneSize == 0 || i == allIdSize) {
                    //先查英文版
                    List<HotelInfo> hotelInfos_EN = repidApi.queryHotel(tempIdsList, supplyCode, RapidConstants.LANG_EN);
                    //先查中文版
                    List<HotelInfo> hotelInfos_CN = repidApi.queryHotel(tempIdsList, supplyCode, RapidConstants.LANG_CN);
                    /**
                     * 第二步：保存供应商酒店房型基本信息
                     */
                    saveSupplyDate(hotelInfos_EN, hotelInfos_CN, hotelCityMap, hotelProvinceMap, type_city, type_province);

                    tempIdsList.clear();
                    System.out.println(i+"-"+hotelId);
                }
            }
        }
        return "同步完成";
    }

    /**
     * 初始保存供应商原始基本数据
     * @param hotelInfos_EN
     * @param hotelInfos_CN
     */
    public void saveSupplyDate(List<HotelInfo> hotelInfos_EN, List<HotelInfo> hotelInfos_CN, Map<String, String> hotelCityMap,Map<String, String> hotelProvinceMap,
                               String type_city,String type_province){
        Map<String,SupplyHotelDTO> supplyHotelDTOMap = new HashMap<>();
        Map<String,SupplyRoomDTO> supplyRoomDTOMap = new HashMap<>();

        //英文版数据封装
        if(CollectionUtils.isNotEmpty(hotelInfos_EN)){
            for(HotelInfo hotelInfo:hotelInfos_EN){
                SupplyHotelDTO supplyHotelDTO = null;
                if(supplyHotelDTOMap.containsKey(hotelInfo.getHotelId())){
                    supplyHotelDTO = supplyHotelDTOMap.get(hotelInfo.getHotelId());
                }else{
                    supplyHotelDTO = new SupplyHotelDTO();
                }
                supplyHotelDTO.setCoHotelId(hotelInfo.getHotelId());
                supplyHotelDTO.setCoHotelEngname(hotelInfo.getHotelName());
                supplyHotelDTO.setCoCountry(hotelInfo.getCountryCode());
                supplyHotelDTO.setCoProvince(hotelInfo.getProvinceName());
                supplyHotelDTO.setCoCity(hotelInfo.getCity());
                supplyHotelDTO.setCoEngAddress1(hotelInfo.getAddress1());
                supplyHotelDTO.setCoEngAddress2(hotelInfo.getAddress2());
                supplyHotelDTO.setCoTel(hotelInfo.getPhone());
                supplyHotelDTO.setCoFax(hotelInfo.getFax());
                supplyHotelDTO.setCoStart(hotelInfo.getRating());
                supplyHotelDTO.setCoLatitude(hotelInfo.getLatitude());
                supplyHotelDTO.setCoLongitude(hotelInfo.getLongitude());
                supplyHotelDTO.setSupplierClass(SupplierClass.EAN.name());
                supplyHotelDTO.setCreateTime(new Date());
                supplyHotelDTO.setRank(hotelInfo.getRank());

                if(hotelCityMap.containsKey(type_city + hotelInfo.getHotelId())){
                    supplyHotelDTO.setCoCityCode(hotelCityMap.get(type_city + hotelInfo.getHotelId()));
                }

                if(hotelProvinceMap.containsKey(type_province + hotelInfo.getHotelId())){
                    supplyHotelDTO.setCoProvinceCode(hotelProvinceMap.get(type_province + hotelInfo.getHotelId()));
                }

                supplyHotelDTOMap.put(hotelInfo.getHotelId(), supplyHotelDTO);

                if(CollectionUtils.isNotEmpty(hotelInfo.getRooms())){
                    for(RoomTypeInfo roomTypeInfo:hotelInfo.getRooms()){
                        String roomUnionKey=hotelInfo.getHotelId()+"-"+roomTypeInfo.getRoomTypeId();
                        SupplyRoomDTO supplyRoomDTO=null;
                        if(supplyRoomDTOMap.containsKey(roomUnionKey)){
                            supplyRoomDTO = supplyRoomDTOMap.get(roomUnionKey);
                        }else{
                            supplyRoomDTO = new SupplyRoomDTO();
                        }
                        supplyRoomDTO.setCoBedType(roomTypeInfo.getBedDesc());
                        supplyRoomDTO.setCoHotelId(hotelInfo.getHotelId());
                        supplyRoomDTO.setCoRoomId(roomTypeInfo.getRoomTypeId());
                        supplyRoomDTO.setCoRoomNameEn(roomTypeInfo.getName());
                        supplyRoomDTO.setSupplierClass(SupplierClass.EAN.name());
                        supplyRoomDTO.setCreateTime(new Date());
                        supplyRoomDTOMap.put(roomUnionKey, supplyRoomDTO);
                    }
                }
            }
        }

        /**
         * 中文版内容封装
         */
        if(CollectionUtils.isNotEmpty(hotelInfos_CN)){
            for(HotelInfo hotelInfo:hotelInfos_CN){
                SupplyHotelDTO supplyHotelDTO = null;
                if(supplyHotelDTOMap.containsKey(hotelInfo.getHotelId())){
                    supplyHotelDTO = supplyHotelDTOMap.get(hotelInfo.getHotelId());
                }else{
                    supplyHotelDTO = new SupplyHotelDTO();
                }
                supplyHotelDTO.setCoHotelId(hotelInfo.getHotelId());
                supplyHotelDTO.setCoHotelCnname(hotelInfo.getHotelName());
                supplyHotelDTO.setCoCountry(supplyHotelDTO.getCoCountry()==null?hotelInfo.getCountryCode():supplyHotelDTO.getCoCountry());
                supplyHotelDTO.setCoCity(supplyHotelDTO.getCoCity()==null?hotelInfo.getCity():supplyHotelDTO.getCoCity());
                supplyHotelDTO.setCoCnAddress1(hotelInfo.getAddress1());
                supplyHotelDTO.setCoCnAddress2(hotelInfo.getAddress2());
                supplyHotelDTO.setCoTel(supplyHotelDTO.getCoTel()==null?hotelInfo.getPhone():supplyHotelDTO.getCoTel());
                supplyHotelDTO.setCoFax(supplyHotelDTO.getCoFax()==null?hotelInfo.getFax():supplyHotelDTO.getCoFax());
                supplyHotelDTO.setCoStart(supplyHotelDTO.getCoStart()==null?hotelInfo.getRating():supplyHotelDTO.getCoStart());
                supplyHotelDTO.setCoLatitude(supplyHotelDTO.getCoLatitude()==null?hotelInfo.getLatitude():supplyHotelDTO.getCoLatitude());
                supplyHotelDTO.setCoLongitude(supplyHotelDTO.getCoLongitude()==null?hotelInfo.getLongitude():supplyHotelDTO.getCoLongitude());
                supplyHotelDTO.setSupplierClass(SupplierClass.EAN.name());
                supplyHotelDTO.setCreateTime(new Date());

                supplyHotelDTOMap.put(hotelInfo.getHotelId(), supplyHotelDTO);

                if(CollectionUtils.isNotEmpty(hotelInfo.getRooms())){
                    for(RoomTypeInfo roomTypeInfo:hotelInfo.getRooms()){
                        String roomUnionKey=hotelInfo.getHotelId()+"-"+roomTypeInfo.getRoomTypeId();
                        SupplyRoomDTO supplyRoomDTO=null;
                        if(supplyRoomDTOMap.containsKey(roomUnionKey)){
                            supplyRoomDTO = supplyRoomDTOMap.get(roomUnionKey);
                        }else{
                            supplyRoomDTO = new SupplyRoomDTO();
                        }
                        supplyRoomDTO.setCoBedType(supplyRoomDTO.getCoBedType()==null?roomTypeInfo.getBedDesc():supplyRoomDTO.getCoBedType());
                        supplyRoomDTO.setCoHotelId(hotelInfo.getHotelId());
                        supplyRoomDTO.setCoRoomId(roomTypeInfo.getRoomTypeId());
                        supplyRoomDTO.setCoRoomNameCn(roomTypeInfo.getName());
                        supplyRoomDTO.setSupplierClass(SupplierClass.EAN.name());
                        supplyRoomDTO.setCreateTime(new Date());
                        supplyRoomDTOMap.put(roomUnionKey, supplyRoomDTO);
                    }
                }
            }
        }

        if(!supplyHotelDTOMap.isEmpty()){
            List<SupplyHotelDTO> supplyHotelDTOList = new ArrayList<>();
            for(String hotelKey:supplyHotelDTOMap.keySet()){
                supplyHotelDTOList.add(supplyHotelDTOMap.get(hotelKey));
            }
            supplyHotelStaticServer.addSupplyHotel(supplyHotelDTOList);
        }

        if(!supplyRoomDTOMap.isEmpty()){
            List<SupplyRoomDTO> supplyRoomDTOList = new ArrayList<>();
            for(String roomKey:supplyRoomDTOMap.keySet()){
                supplyRoomDTOList.add(supplyRoomDTOMap.get(roomKey));
            }
            supplyHotelStaticServer.addSupplyRoom(supplyRoomDTOList);
        }
        initAndAddHotelDate(hotelInfos_EN, hotelInfos_CN, hotelCityMap,hotelProvinceMap, type_city, type_province);
    }

    /**
     * 处理酒店新增酒店映射
     * @param hotelInfos_EN
     * @param hotelInfos_CN
     * @param hotelCityMap
     * @param hotelProvinceMap
     * @param type_city
     * @param type_province
     */
    private void initAndAddHotelDate(List<HotelInfo> hotelInfos_EN, List<HotelInfo> hotelInfos_CN, Map<String, String> hotelCityMap,Map<String, String> hotelProvinceMap,
                               String type_city,String type_province){
        Map<String, HotelInfoRequestDTO> hotelInfoMap = new HashMap<>();
        Map<String, RoomTypeRequestDTO> roomDTOMap = new HashMap<>();

        //1、英文版数据封装
        if(CollectionUtils.isNotEmpty(hotelInfos_EN)){
            for(HotelInfo hotelInfo:hotelInfos_EN){
                HotelInfoRequestDTO hotelInfoRequest = null;
                if(hotelInfoMap.containsKey(hotelInfo.getHotelId())){
                    hotelInfoRequest = hotelInfoMap.get(hotelInfo.getHotelId());
                }else{
                    hotelInfoRequest = new HotelInfoRequestDTO();
                    hotelInfoMap.put(hotelInfo.getHotelId(),hotelInfoRequest);
                }

                hotelInfoRequest.setCreator(SystemConstants.EAN_CREATER+hotelInfo.getHotelId());
                hotelInfoRequest.setCreateTime(new Date());
                hotelInfoRequest.setHotelName(hotelInfo.getHotelName());
                hotelInfoRequest.setEngHotelName(hotelInfo.getHotelName()!=null?hotelInfo.getHotelName().trim():null);
                if(hotelInfoRequest.getEngHotelName() != null && hotelInfoRequest.getEngHotelName().length() > 64){
                    hotelInfoRequest.setEngHotelName(hotelInfoRequest.getEngHotelName().substring(0,64));
                }
                hotelInfoRequest.setCountry(hotelInfo.getCountryCode());
                hotelInfoRequest.setPhone(hotelInfo.getPhone());
                hotelInfoRequest.setFax(hotelInfo.getFax());
                hotelInfoRequest.setGoogleLatitude(new BigDecimal(hotelInfo.getLatitude()));
                hotelInfoRequest.setGoogleLongitude(new BigDecimal(hotelInfo.getLongitude()));
                if(hotelCityMap.containsKey(type_city + hotelInfo.getHotelId())){
                    hotelInfoRequest.setCityCode(hotelCityMap.get(type_city + hotelInfo.getHotelId()));
                }
                hotelInfoRequest.setCityName(hotelInfo.getCity());

                String address=hotelInfo.getAddress2();
                if(StringUtil.isValidString(address) && StringUtil.isValidString(hotelInfo.getAddress1())){
                    address = address+", "+hotelInfo.getAddress1();
                }else if(!StringUtil.isValidString(hotelInfo.getAddress2())){
                    address = hotelInfo.getAddress1();
                }
                hotelInfoRequest.setEngHotelAddress(address);
                if(null != hotelInfo.getRating()){
                    hotelInfoRequest.setHotelStar(EanMapConstants.HOTEL_START.get(hotelInfo.getRating()));//星级转换
                }

                PropertyContent content = hotelInfo.getPropertyContent();

                //主题
                if(content.getCategory() != null && content.getCategory().getId() != null && EanMapConstants.HOTEL_CATEGORY.get(content.getCategory().getId())!=null){
                    String[] theme = new String[1];
                    theme[0] = EanMapConstants.HOTEL_CATEGORY.get(content.getCategory().getId()).toString();
                    hotelInfoRequest.setTheme(theme);
                }
                //房间总数

                //酒店介绍
                if(content.getDescriptions() != null){
                    String desc="";
                    for(String temp:content.getDescriptions().keySet()){

                        String addDesc=desc + content.getDescriptions();
                        if((desc + addDesc).length() > 500){
                            break;
                        }
                        desc = desc + addDesc;
                    }
                    hotelInfoRequest.setIntroduction(desc);
                }

                if(content.getCheckin()!=null && content.getCheckin().getBegin_time() != null){
                    hotelInfoRequest.setCheckInTime(initCheckTime(content.getCheckin().getBegin_time()));
                }

                if(content.getCheckout()!=null && content.getCheckout().getTime() != null){
                    hotelInfoRequest.setCheckOutTime(initCheckTime(content.getCheckout().getTime()));
                }

                //是否允许携带宠物
                if(content.getThemes() != null){
                    for(String themeKey:content.getThemes().keySet()){
                        RefObj refObj = content.getThemes().get(themeKey);
                        if(refObj != null && "2338".equals(refObj.getId())){
                            hotelInfoRequest.setPet(1);//允许携带宠物，没说明则不设置
                        }else if (refObj != null && "2050".equals(refObj.getId())){
                            hotelInfoRequest.setPet(0);
                        }
                    }
                }
                //房间总数
                if(content.getStatistics() != null){
                    for(String staticsKey:content.getStatistics().keySet()){
                        RefObj refObj = content.getStatistics().get(staticsKey);
                        if(refObj != null && "52".equals(refObj.getId())){
                            hotelInfoRequest.setRoomTotalNum(Integer.valueOf(refObj.getValue().replace(" ","")));
                            break;
                        }
                    }
                }

                //信用卡类型
                if(content.getOnsite_payments() != null && content.getOnsite_payments().getTypes() != null){
                    List<String> creditCards = new ArrayList<>();
                    int i = 0;
                    for(String typeKey:content.getOnsite_payments().getTypes().keySet()){
                        RefObj refObj = content.getOnsite_payments().getTypes().get(typeKey);

                        if(EanMapConstants.PAYMENTS.containsKey(refObj.getId())){
                            creditCards.add(EanMapConstants.PAYMENTS.get(refObj.getId()));
                            i++;
                        }
                    }
                    if(creditCards.size() > 0){
                        hotelInfoRequest.setCreditCard(creditCards.toArray((new String[creditCards.size()])));
                    }
                }
                //酒店设施
                if(content.getAmenities() != null){
                    Map<String, HotelFacilityDTO> hotelFacilityMap = new HashMap<>();

                    for(Integer key:content.getAmenities().keySet()){
                        AmenitiesEnum amenitiesEnum = AmenitiesEnum.getEnumNameyByID(key);
                        if(amenitiesEnum != null){
                            HotelFacilityDTO hotelFacility = new HotelFacilityDTO();
                            hotelFacility.setFacilityName(amenitiesEnum.getFacilityName());
                            hotelFacility.setFacilityType(amenitiesEnum.getFacilityType());
                            hotelFacilityMap.put(hotelFacility.getFacilityName(),hotelFacility);
                        }
                    }

                    if(!hotelFacilityMap.isEmpty()){
                        List<HotelFacilityDTO> facilityList = new ArrayList<>();
                        for(String name:hotelFacilityMap.keySet()){
                            HotelFacilityDTO hotelFacility = hotelFacilityMap.get(name);
                            facilityList.add(hotelFacility);
                        }
                        hotelInfoRequest.setFacilityList(facilityList);
                    }
                }

                //房型
                if(content.getRooms() != null){
                    for(String coRoomId:content.getRooms().keySet()){
                        RoomContent coRoom = content.getRooms().get(coRoomId);
                        String roomUnionKey=hotelInfo.getHotelId()+"-"+coRoom.getId();
                        RoomTypeRequestDTO roomDTO=null;
                        if(roomDTOMap.containsKey(roomUnionKey)){
                            roomDTO = roomDTOMap.get(roomUnionKey);
                        }else{
                            roomDTO = new RoomTypeRequestDTO();
                        }
                        roomDTO.setEngRoomTypeName(coRoom.getName());
                        if(roomDTO.getEngRoomTypeName() != null && roomDTO.getEngRoomTypeName().length() >= 64){
                            roomDTO.setEngRoomTypeName(roomDTO.getEngRoomTypeName().substring(0,63));
                        }
                        roomDTO.setCreator(SystemConstants.EAN_CREATER+coRoomId);
                        roomDTO.setCreateTime(new Date());

                        if(coRoom.getDescriptions() != null && coRoom.getDescriptions().get("overview") != null) {
                            String roomDesc = coRoom.getDescriptions().get("overview");
                            roomDTO.setRoomTypeDescribe(roomDesc);

                            if(roomDesc != null && roomDTO.getRoomTypeDescribe().length() >500 ){
                                roomDTO.setRoomTypeDescribe(roomDTO.getRoomTypeDescribe().substring(0,500));
                            }

                            //面积截取
                            if(roomDesc.contains("foot") && roomDesc.contains("meter")){
                                int begin = roomDesc.indexOf("foot")+4;
                                int end = roomDesc.indexOf("meter");
                                if(begin < end){
                                    String meterDes=roomDesc.substring(begin,end).replace(" ","");
                                    String meter="";
                                    if(meterDes != null && !"".equals(meterDes)){
                                        for(int i=0;i<meterDes.length();i++){
                                            if(meterDes.charAt(i)>=48 && meterDes.charAt(i)<=57){
                                                meter+=meterDes.charAt(i);
                                            }
                                        }
                                    }
                                    roomDTO.setArea(meter);
                                }
                            }
                            //无窗
                            if(roomDesc.contains("No windows")){
                                roomDTO.setIsWindow(0);
                            }

                            //wifi
                            if(roomDesc.contains("Free WiFi")){
                                roomDTO.setIsWifi(1);
                            }

                            //是否无烟
                            if(roomDesc.contains("Non Smoking") || roomDesc.contains("Non-Smoking")){
                                roomDTO.setIsSmokeless(1);
                            } else if(roomDesc.contains("Smoking") || roomDesc.contains("Non-Smoking")){
                                roomDTO.setIsSmokeless(0);
                            }

                            //宽带
                            if(roomDesc.contains("wired Internet")){
                                roomDTO.setIsWired(1);//免费有限网络
                            }

                            //加床
                            if(roomDesc.contains("extra beds") && roomDesc.contains("No ")){
                                roomDTO.setIsExtraBed("0");
                            }else if(roomDesc.contains("extra beds available on request") || roomDesc.contains("extra beds")){
                                roomDTO.setIsExtraBed("1");
                            }
                        }

                        //床型识别，面积识别等
                        if(coRoom.getBed_groups() != null){
                            List<BedTypeDTO> bedTypes = new ArrayList<>();
                            for(String bedGroupKey:coRoom.getBed_groups().keySet()){
                                BedGroup bedGroup = coRoom.getBed_groups().get(bedGroupKey);
                                for(Configuration configuration:bedGroup.getConfiguration()){
                                    Integer type = EanBedTypeEnum.getKeyByEanType(configuration.getType());
                                    if(type==null){
                                        continue;
                                    }
                                    BedTypeDTO bedTypeDTO = new BedTypeDTO();
                                    bedTypeDTO.setBedType(type);
                                    bedTypeDTO.setNum(configuration.getQuantity());
                                    bedTypes.add(bedTypeDTO);
                                }
                            }
                            roomDTO.setBedTypeList(bedTypes.size() > 0? bedTypes:null);
                        }


                        roomDTOMap.put(roomUnionKey, roomDTO);
                    }
                }
            }
        }

        //2、中文版数据封装
        if(CollectionUtils.isNotEmpty(hotelInfos_CN)) {
            for (HotelInfo hotelInfo : hotelInfos_CN) {
                HotelInfoRequestDTO hotelInfoRequest = null;
                if (hotelInfoMap.containsKey(hotelInfo.getHotelId())) {
                    hotelInfoRequest = hotelInfoMap.get(hotelInfo.getHotelId());
                } else {
                    hotelInfoRequest = new HotelInfoRequestDTO();
                    hotelInfoMap.put(hotelInfo.getHotelId(),hotelInfoRequest);
                }

                hotelInfoRequest.setCreator(SystemConstants.EAN_CREATER+hotelInfo.getHotelId());
                hotelInfoRequest.setCreateTime(new Date());
                hotelInfoRequest.setHotelName(hotelInfo.getHotelName());
                hotelInfoRequest.setCountry(hotelInfoRequest.getCountry()==null?hotelInfo.getCountryCode():hotelInfoRequest.getCountry());
                hotelInfoRequest.setPhone(hotelInfoRequest.getPhone()==null?hotelInfo.getPhone():hotelInfoRequest.getPhone());
                hotelInfoRequest.setFax(hotelInfoRequest.getFax()==null?hotelInfo.getFax():hotelInfoRequest.getFax());
                hotelInfoRequest.setGoogleLatitude(hotelInfoRequest.getGoogleLatitude()==null?new BigDecimal(hotelInfo.getLatitude()):hotelInfoRequest.getGoogleLatitude());
                hotelInfoRequest.setGoogleLongitude(hotelInfoRequest.getGoogleLongitude()==null?new BigDecimal(hotelInfo.getLongitude()):hotelInfoRequest.getGoogleLongitude());
                if(hotelInfoRequest.getCityCode()==null && hotelCityMap.containsKey(type_city + hotelInfo.getHotelId())){
                    hotelInfoRequest.setCityCode(hotelCityMap.get(type_city + hotelInfo.getHotelId()));
                }
                hotelInfoRequest.setCityName(hotelInfoRequest.getCityName()==null?hotelInfo.getCity():hotelInfoRequest.getCityName());

                //港澳酒店城市数据
                if(hotelInfo.getCountryCode().equals("HK")){
                    hotelInfoRequest.setCountry("CN");
                    hotelInfoRequest.setCityCode("HKG");
                    hotelInfoRequest.setCityName("香港");
                }else if(hotelInfo.getCountryCode().equals("HK")){
                    hotelInfoRequest.setCountry("CN");
                    hotelInfoRequest.setCityCode("MAC");
                    hotelInfoRequest.setCityName("澳门");
                }

                String address=hotelInfo.getAddress2();
                if(StringUtil.isValidString(address) && StringUtil.isValidString(hotelInfo.getAddress1())){
                    address = address+", "+hotelInfo.getAddress1();
                }else if(!StringUtil.isValidString(hotelInfo.getAddress2())){
                    address = hotelInfo.getAddress1();
                }
                hotelInfoRequest.setHotelAddress(address);

                if(hotelInfoRequest.getHotelStar() == null && null != hotelInfo.getRating()){
                    hotelInfoRequest.setHotelStar(EanMapConstants.HOTEL_START.get(hotelInfo.getRating()));//星级转换
                }

                PropertyContent content = hotelInfo.getPropertyContent();

                //酒店介绍
                if(content.getDescriptions() != null){
                    String desc="";
                    for(String temp:content.getDescriptions().keySet()){
                        String addDesc=desc + content.getDescriptions().get(temp).replace(" ","");
                        if((desc + addDesc).length() >= 500){
                            break;
                        }
                        desc = desc + addDesc;
                    }
                    hotelInfoRequest.setIntroduction(desc);
                }

                //酒店备注
                if(content.getPolicies() != null && content.getPolicies().containsKey("know_before_you_go")){
                    String tmp=content.getPolicies().get("know_before_you_go");
                    hotelInfoRequest.setOrderRemark(tmp.replace(" ",""));

                    if(hotelInfoRequest.getOrderRemark().length() >= 500){
                        hotelInfoRequest.setOrderRemark(hotelInfoRequest.getOrderRemark().substring(0,500));
                    }
                }

                //其他政策
                if(content.getFees() != null){
                    String mandatory = content.getFees().getMandatory()!=null?content.getFees().getMandatory().replace(" ",""):null;
                    String optional = content.getFees().getOptional()!=null?content.getFees().getOptional().replace(" ",""):null;
                    if(mandatory != null && mandatory.length() < 500){
                        hotelInfoRequest.setOtherPolicy(mandatory);
                        if(optional != null && (mandatory+optional).length() < 500){
                            hotelInfoRequest.setOtherPolicy(mandatory+optional);
                        }
                    }else if(optional != null && optional.length() < 500){
                        hotelInfoRequest.setOtherPolicy(optional);
                    }
                }

                //房型
                if(content.getRooms() != null){
                    for(String coRoomId:content.getRooms().keySet()){
                        RoomContent coRoom = content.getRooms().get(coRoomId);
                        String roomUnionKey=hotelInfo.getHotelId()+"-"+coRoom.getId();
                        RoomTypeRequestDTO roomDTO=null;
                        if(roomDTOMap.containsKey(roomUnionKey)){
                            roomDTO = roomDTOMap.get(roomUnionKey);
                        }else{
                            roomDTO = new RoomTypeRequestDTO();
                        }
                        roomDTO.setCreator(SystemConstants.EAN_CREATER+coRoomId);
                        roomDTO.setCreateTime(new Date());
                        roomDTO.setRoomTypeName(coRoom.getName());
                        if(roomDTO.getRoomTypeName() != null && roomDTO.getRoomTypeName().length() >= 64){
                            roomDTO.setRoomTypeName(roomDTO.getRoomTypeName().substring(0,63));
                        }
                        if(coRoom.getDescriptions() != null){
                            roomDTO.setRoomTypeDescribe(coRoom.getDescriptions().get("overview"));
                            //中文描述需要去空格
                            roomDTO.setRoomTypeDescribe(roomDTO.getRoomTypeDescribe()!=null?roomDTO.getRoomTypeDescribe().replace(" ",""):null);
                            if(roomDTO.getRoomTypeDescribe().length() >500 ){
                                roomDTO.setRoomTypeDescribe(roomDTO.getRoomTypeDescribe().substring(0,500));
                            }
                        }

                        //床型识别，面积识别等
                        roomDTOMap.put(roomUnionKey, roomDTO);
                    }
                }
            }
        }

        //新增酒店数据Map<供应商酒店id,本地酒店id>
        Map<String, Long> hotelIdMap = new HashMap<>();
        //3、新增酒店数据，新增成功后自动添加酒店映射
        if(!hotelInfoMap.isEmpty()) {
            for(String coHotelId:hotelInfoMap.keySet()){
                HotelInfoRequestDTO hotelInfoRequest = hotelInfoMap.get(coHotelId);
                ResponseDTO<HotelInfoResponseDTO> response = hotelInfoSyncService.saveOrUpdateHotel(hotelInfoRequest);
                if(response!=null && response.getModel()!=null && response.getModel().getHotelId()!=null) {
                    //新增酒店映射
                    HotelMappingDTO hotelMpRequest = new HotelMappingDTO();
                    hotelMpRequest.setIsActive(1);
                    hotelMpRequest.setCoCityCode(hotelInfoRequest.getCityCode());
                    hotelMpRequest.setCoHotelId(coHotelId);
                    hotelMpRequest.setCoHotelName(hotelInfoRequest.getEngHotelName());
                    hotelMpRequest.setCreateDate(new Date());
                    hotelMpRequest.setCreator(SystemConstants.SYSTEM_OPERATOR);
                    hotelMpRequest.setHotelId(response.getModel().getHotelId());
                    hotelMpRequest.setSupplierClass(SupplierClass.EAN.name());

                    supplyDataMappingServer.addHotelMapping(hotelMpRequest);
                    hotelIdMap.put(coHotelId, hotelMpRequest.getHotelId());
                }
            }
        }

        //4、新增房型数据，新增成功后自动添加映射
        if(!roomDTOMap.isEmpty()){
            for(String roomUnionKey:roomDTOMap.keySet()){
                RoomTypeRequestDTO roomRequest = roomDTOMap.get(roomUnionKey);
                String coHotelId = roomUnionKey.split("-")[0];
                String coRoomId = roomUnionKey.split("-")[1];

                if(hotelIdMap.get(coHotelId) != null){
                    roomRequest.setHotelId(hotelIdMap.get(coHotelId));
                }

                if(roomRequest.getHotelId() != null){
                    ResponseDTO responseDTO = roomTypeSyncService.saveOrUpdateRoomType(roomRequest);
                    if(responseDTO!=null && responseDTO.getModel()!=null){
                        RoomMappingDTO roomMappingDTO = new RoomMappingDTO();
                        roomMappingDTO.setIsActive(1);
                        roomMappingDTO.setCoHotelId(coHotelId);
                        roomMappingDTO.setCoRoomId(coRoomId);
                        roomMappingDTO.setCoRoomName(roomRequest.getEngRoomTypeName());
                        roomMappingDTO.setCreateDate(new Date());
                        roomMappingDTO.setCreator(SystemConstants.SYSTEM_OPERATOR);
                        roomMappingDTO.setRoomId((Long) responseDTO.getModel());
                        roomMappingDTO.setRoomName(roomRequest.getEngRoomTypeName());
                        supplyDataMappingServer.addRoomMapping(roomMappingDTO);
                    }
                }
            }
        }
    }

    private String initCheckTime(String checkTime){
        if(!checkTime.contains(":")){
            return null;
        }
        checkTime = checkTime.replace("noon","12:00");
        String hourStr = checkTime.split(":")[0];
        if(hourStr.length() >2){
            return null;
        }
        Integer hour = Integer.valueOf(hourStr);
        String mins = checkTime.split(":")[1].substring(0,2);

        if(checkTime.contains("PM") && hour != 12){
            hour = hour+12;
        }
        return hour+":"+mins;
    }
}
